package com.sgb.kjwl.viewmodel.self.logistics;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.JsonObject;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.transport.CargoDistanceEntity;
import com.sgb.kjwl.model.entity.transport.CargoEntity;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.DiyFieldEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourcePlaceEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.link.utils.RoundDialogHelper;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReleaseBiddingCargoModel extends AndroidViewModel {
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldHandleType = new MutableLiveData<>();
    public MutableLiveData<CargoDistanceEntity> ldDistance = new MutableLiveData<>();
    public MutableLiveData<CargoPublishEntity> ldPublish = new MutableLiveData<>();
    public MutableLiveData<Integer> ldJump = new MutableLiveData<>();
    public MutableLiveData<Boolean> ldLocation = new MutableLiveData<>();
    //装卸地缓存数据
    private final CargoPublishEntity.LocationEntity[] mCacheLocationList;
    //新数据装卸模式，判断数据是否为新发布货源
    private final Set<String> mNewLoadModeSet = new HashSet<>(Arrays.asList("11", "12", "21", "22"));

    public ReleaseBiddingCargoModel(@NonNull Application application) {
        super(application);
        mCacheLocationList = new CargoPublishEntity.LocationEntity[4];
        resetLocationCache();
    }

    /**
     * 重置装卸地缓存
     */
    private void resetLocationCache() {
        mCacheLocationList[0] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_ONE, 0);
        mCacheLocationList[1] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_TWO, 1);
        mCacheLocationList[2] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_THREE, 2);
        mCacheLocationList[3] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_FOUR, 3);
    }

    /**
     * 装载方式
     */
    public void getHandleType() {
        //11：一装一卸 12：一装两卸 21：两装一卸 22：两装两卸
        List<GoodsInfoTypeEntity3> list = new ArrayList<>();
        list.add(new GoodsInfoTypeEntity3("11", "一装一卸"));
        list.add(new GoodsInfoTypeEntity3("12", "一装两卸"));
        list.add(new GoodsInfoTypeEntity3("21", "两装一卸"));
        list.add(new GoodsInfoTypeEntity3("22", "两装两卸"));
        ldHandleType.postValue(list);
    }

    /**
     * 获取货源详情，编辑时使用
     */
    public void getDetail(Context context, String no) {
        getDetail(context, no, false);
    }

    public void getDetail(Context context, String no, boolean isHistory) {
        DialogHelper.showProgressDialog(context, "请求中...");
        String isLogin = UserOperating.getInstance().isLogged() ? "true" : "false";
        NewAPIManager.getInstance().getLogisticsAPI().getCargoDetail(isLogin, no).enqueue(new ICallBack<BaseEntity<CargoEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CargoEntity> data) {
                checkGoodsType(context, data.getData(), isHistory);
            }

            @Override
            public void onFail() {
                ldPublish.postValue(null);
            }
        });
    }


    public void checkGoodsType(Context context, CargoEntity entity, boolean isHistory) {
        NewAPIManager.getInstance().getLogisticsAPI().checkGoodsType(entity.getGoodsTypeNo(), entity.getSecondGoodsTypeNo()).enqueue(new Callback<BaseEntity<String>>() {
            @Override
            public void onResponse(Call<BaseEntity<String>> call, Response<BaseEntity<String>> response) {
                if (response.body() == null || response.body().getCode() == null)
                    return;
                if (response.body().getCode().equals("200")) {
                    assemblyData(entity, isHistory);
                } else {
                    String content = isHistory ? "平台[货物类型]已调整，使用历史货源发布需重新选择该信息" : "平台[货物类型]已调整，编辑货源需重新选择该信息";
                    RoundDialogHelper.showSingleDialog(context, "提示", content, "我知道了", true, com.sgb.trip.R.color.color_5792FD, new RoundDialogHelper.DialogFunction() {
                        @Override
                        public void normalRoundDialog() {
                            entity.setGoodsTypeNo(null);
                            entity.setSecondGoodsTypeNo(null);
                            entity.setSecondGoodsTypeName(null);
                            entity.setGoodsTypeName(null);
                            assemblyData(entity, isHistory);
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<String>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }

        });
    }

    /**
     * 组装数据，将接口返回的数据重新组装成页面逻辑需要的数据
     */
    public void assemblyData(CargoEntity old, boolean isHistory) {
        if (old == null) {
            ldPublish.postValue(null);
            return;
        }
        CargoPublishEntity entity = new CargoPublishEntity();
        entity.setHistory(isHistory);
        //重组数据
        if (!isHistory) {
            //编辑货源组装no数据
            entity.setId(old.getId());
            entity.setNo(old.getNo());
        } else if (ldPublish.getValue() != null && !TextUtils.isEmpty(ldPublish.getValue().getNo())) {
            //编辑货源时选择历史货源组装原no数据
            entity.setId(ldPublish.getValue().getId());
            entity.setNo(ldPublish.getValue().getNo());
        }
        entity.setPattern(old.getPattern());
        //新数据设置装卸方式，老数据默认一装一卸
        if (mNewLoadModeSet.contains(old.getHandleTypeNo())) {
            //设置装卸方式
            entity.setLoadModeNo(old.getHandleTypeNo());
            entity.setLoadMode(old.getHandleTypeName());
        } else {
            entity.setLoadModeNo("11");
            entity.setLoadMode("一装一卸");
        }
        //设置发货人信息，2.0.1增加装货单位和装货方式
        mCacheLocationList[0].setGoodsUnit(DefaultUtil.getString(old.getSendGoodsUnit()));
        mCacheLocationList[0].setContact(DefaultUtil.getString(old.getSendPeople()));
        mCacheLocationList[0].setTelPhone(DefaultUtil.getString(old.getSendPhone()));
        //设置收货人信息，2.0.1增加卸货单位和卸货方式
        mCacheLocationList[3].setGoodsUnit(DefaultUtil.getString(old.getReceiveGoodsUnit()));
        mCacheLocationList[3].setContact(DefaultUtil.getString(old.getReceptionPeople()));
        mCacheLocationList[3].setTelPhone(DefaultUtil.getString(old.getReceptionPhone()));
        //设置装卸数据
        GoodsSourcePlaceEntity place = old.getGoodsSourcePlace();
        if (place != null) {
            if (place.getLatitude() != null && place.getLongitude() != null) {
                mCacheLocationList[0].setLatitude(place.getLatitude());
                mCacheLocationList[0].setLongitude(place.getLongitude());
                mCacheLocationList[0].setProvinceNo(place.getProvinceNo());
                mCacheLocationList[0].setProvince(place.getProvinceName());
                mCacheLocationList[0].setCityNo(place.getCityNo());
                mCacheLocationList[0].setCity(place.getCityName());
                mCacheLocationList[0].setDistrictNo(place.getDistrictNo());
                mCacheLocationList[0].setDistrict(place.getDistrictName());
                mCacheLocationList[0].setAddress(place.getDetailAddress());
            } else {
                mCacheLocationList[0] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_ONE, 0);
            }
            if (place.getViaSendLatitude() != null && place.getViaSendLongitude() != null) {
                mCacheLocationList[1].setLatitude(place.getViaSendLatitude());
                mCacheLocationList[1].setLongitude(place.getViaSendLongitude());
                mCacheLocationList[1].setProvinceNo(place.getViaSendProvinceNo());
                mCacheLocationList[1].setProvince(place.getViaSendProvinceName());
                mCacheLocationList[1].setCityNo(place.getViaSendCityNo());
                mCacheLocationList[1].setCity(place.getViaSendCityName());
                mCacheLocationList[1].setDistrictNo(place.getViaSendDistrictNo());
                mCacheLocationList[1].setDistrict(place.getViaSendDistrictName());
                mCacheLocationList[1].setAddress(place.getViaSendDetailAddress());
            } else {
                mCacheLocationList[1] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_TWO, 1);
            }
            if (place.getViaDestLatitude() != null && place.getViaDestLongitude() != null) {
                mCacheLocationList[2].setLatitude(place.getViaDestLatitude());
                mCacheLocationList[2].setLongitude(place.getViaDestLongitude());
                mCacheLocationList[2].setProvinceNo(place.getViaDestProvinceNo());
                mCacheLocationList[2].setProvince(place.getViaDestProvinceName());
                mCacheLocationList[2].setCityNo(place.getViaDestCityNo());
                mCacheLocationList[2].setCity(place.getViaDestCityName());
                mCacheLocationList[2].setDistrictNo(place.getViaDestDistrictNo());
                mCacheLocationList[2].setDistrict(place.getViaDestDistrictName());
                mCacheLocationList[2].setAddress(place.getViaDestDetailAddress());
            } else {
                mCacheLocationList[2] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_THREE, 2);
            }
            if (place.getDestLatitude() != null && place.getDestLongitude() != null) {
                mCacheLocationList[3].setLatitude(place.getDestLatitude());
                mCacheLocationList[3].setLongitude(place.getDestLongitude());
                mCacheLocationList[3].setProvinceNo(place.getDestProvinceNo());
                mCacheLocationList[3].setProvince(place.getDestProvinceName());
                mCacheLocationList[3].setCityNo(place.getDestCityNo());
                mCacheLocationList[3].setCity(place.getDestCityName());
                mCacheLocationList[3].setDistrictNo(place.getDestDistrictNo());
                mCacheLocationList[3].setDistrict(place.getDestDistrictName());
                mCacheLocationList[3].setAddress(place.getDestDetailAddress());
            } else {
                mCacheLocationList[3] = new CargoPublishEntity.LocationEntity(SingleItemConstant.TYPE_FOUR, 3);
            }
        } else {
            //重置装卸地数据
            resetLocationCache();
        }
        //装货时间
        long currentTime = DateUtils.getCustomizeDayMorning(0, System.currentTimeMillis()).getTime();
        if (isHistory) {
            //历史货源装货开始时间大于当前时间则填入数据
            if (old.getShipmentTime() != null && old.getShipmentTime() >= currentTime) {
                entity.setBeginTime(old.getShipmentTime());
                entity.setEndTime(old.getShipmentEndTime());
                //装货开始时间点
                entity.setStartPointTime(old.getStartPointTime());
                //装货结束时间点
                entity.setEndPointTime(old.getEndPointTime());
            }
        } else {
            //编辑货源直接填入数据
            entity.setBeginTime(old.getShipmentTime());
            entity.setEndTime(old.getShipmentEndTime());
            //装货开始时间点
            entity.setStartPointTime(old.getStartPointTime());
            //装货结束时间点
            entity.setEndPointTime(old.getEndPointTime());
        }
        //报价截止时间
        if (old.getPattern() == 1 && old.getEndTime() != null && old.getEndTime() >= currentTime) {
            entity.setBiddingEndTime(old.getEndTime());
        }
        //货物信息,货物类型对应不上，则货物信息全部信息不填入；
        if (old.getIsGoodsType() != 0 && !TextUtils.isEmpty(old.getGoodsTypeNo())) {
            entity.setGoodsModeNo(old.getGoodsTypeNo());
            entity.setGoodsModeName(TextUtils.isEmpty(old.getSecondGoodsTypeName()) ? old.getGoodsTypeName() : old.getSecondGoodsTypeName());
            entity.setSecondGoodsTypeNo(old.getSecondGoodsTypeNo());
        }
        if (!TextUtils.isEmpty(old.getWeight())) {
            entity.setGoodsWeight(NumberUtil.convertToDouble(old.getWeight()));
        }
        if (!TextUtils.isEmpty(old.getVolume())) {
            entity.setGoodsVolume(NumberUtil.convertToDouble(old.getVolume()));
        }
        if (!TextUtils.isEmpty(old.getPerformanceBond())) {
            //2.0.1增加履约保证金
            entity.setPerformanceBond(NumberUtil.convertToDouble(old.getPerformanceBond()));
        }
        //2.0.8 历史货源运费方式为趟的清空运费数据
        if (entity.getFreightType() == CargoPublishEntity.FreightMode.MODE_ONCE) {
            entity.setFreight(0);
            entity.setFreightMode(0);
            entity.setTotalFreight(0);
        } else {
            entity.setFreight(NumberUtil.convertToDouble(old.getFreight()));
            entity.setFreightMode(NumberUtil.convertToInt(old.getFreightUnit()));
            entity.setTotalFreight(NumberUtil.convertToDouble(old.getAllFreight()));
        }
        //自定义字段
        if (ArrayUtil.isNotNullAndEmpty(old.getDiyField())) {
            List<SingleItemEntity> diyList = new ArrayList<>();
            for (DiyFieldEntity diy : old.getDiyField()) {
                diyList.add(new SingleItemEntity(diy.getKey(), diy.getValue()));
            }
            entity.setCustomList(diyList);
        }
        if (!TextUtils.isEmpty(old.getCompanyNo())) {
            entity.setCompanyNo(old.getCompanyNo());
            entity.setCompany(old.getCompanyName());
        }
        if (!TextUtils.isEmpty(old.getTeamNo())) {
            entity.setCompanyNo(old.getTeamNo());
            entity.setCompany(old.getTeamName());
        }
        //发票是否改变
        entity.setInvoiceChanges(old.isInvoiceChanges());
        if (!TextUtils.isEmpty(old.getPayType())) {
            entity.setPayType(old.getPayType());
        }
        if (!TextUtils.isEmpty(old.getInvoice())) {
            entity.setInvoice(old.getInvoice());
        }
        if (!TextUtils.isEmpty(old.getInvoiceNo())) {
            entity.setInvoiceNo(old.getInvoiceNo());
        }
        if (!TextUtils.isEmpty(old.getTariff())) {
            entity.setTariff(NumberUtil.convertToDouble(old.getTariff()));
        }
        if (!TextUtils.isEmpty(old.getInvoicingCompanyName())) {
            entity.setInvoicingCompanyName(old.getInvoicingCompanyName());
        }
        if (!TextUtils.isEmpty(old.getInvoicingTaxNumber())) {
            entity.setInvoicingTaxNumber(old.getInvoicingTaxNumber());
        }
        if (!TextUtils.isEmpty(old.getInvoicingAddress())) {
            entity.setInvoicingAddress(old.getInvoicingAddress());
        }
        if (!TextUtils.isEmpty(old.getInvoicingCompanyPhone())) {
            entity.setInvoicingCompanyPhone(old.getInvoicingCompanyPhone());
        }
        if (!TextUtils.isEmpty(old.getInvoicingBank())) {
            entity.setInvoicingBank(old.getInvoicingBank());
        }
        if (!TextUtils.isEmpty(old.getInvoicingBankAccount())) {
            entity.setInvoicingBankAccount(old.getInvoicingBankAccount());
        }
        if (!TextUtils.isEmpty(old.getInvoicingBankNumber())) {
            entity.setInvoicingBankNumber(old.getInvoicingBankNumber());
        }
        //2.0.6新增字段
        //装车要求
        if (old.getLoadRequire() != null) {
            entity.setRequire(NumberUtil.convertToInt(old.getLoadRequire()));
        }
        //2.0.8新增字段
        entity.setSpecification(old.getSpecification());
        if (old.getIncludeTax() != null) {
            entity.setIncludeTax(old.getIncludeTax());
        }
        if (old.getDamagePromise() != null) {
            entity.setDamageAgreement(old.getDamagePromise());
        }
        if (old.getDamageCompensation() != null) {
            entity.setDamageCompensation(old.getDamageCompensation());
        }
        entity.setOtherSettlementReq(old.getOtherSettlementRequire());
        if (!TextUtils.isEmpty(old.getOfferType())) {
            entity.setQuotationQualification(new boolean[]{true, true, true});
            entity.getQuotationQualification()[0] = old.getOfferType().contains("1");
            entity.getQuotationQualification()[1] = old.getOfferType().contains("2");
            entity.getQuotationQualification()[2] = old.getOfferType().contains("3");
        } else {
            entity.setQuotationQualification(null);
        }
        if (old.getRegisteredMoney() != null) {
            entity.setRegisteredCapital(old.getRegisteredMoney());
        }
        if (old.getMotorcadeSize() != null) {
            entity.setFleetSize(old.getMotorcadeSize());
        }
        entity.setTransportationQualification(old.getTransportationQualification());
        entity.setOtherRequirements(old.getOtherOfferRequire());
        entity.setProjectName(old.getProjectName());
        entity.setProjectAddress(old.getProjectAddress());
        entity.setProjectDesc(old.getProjectDesc());
        entity.setTransportReq(old.getTransportationQuire());
        entity.setPartyAAgreement(old.getPartyDuty());
        entity.setPartyBAgreement(old.getSecondPartyDuty());
        entity.setBreachOfContract(old.getRenegePromise());
        entity.setTerminationAgreement(old.getEndContractPromise());
        //老数据设置老版本的联系人信息
        if (old.getContactInfo() == null && !TextUtils.isEmpty(old.getContrcts())) {
            List<CargoPublishEntity.ContactInfoEntity> contactInfo = new ArrayList<>();
            CargoPublishEntity.ContactInfoEntity contact = new CargoPublishEntity.ContactInfoEntity();
            contact.setContrcts(old.getContrcts());
            contact.setContrctsNumber(old.getContrctsNumber());
            contactInfo.add(contact);
            old.setContactInfo(contactInfo);
        }
        entity.setContactInfo(old.getContactInfo());
        ldPublish.postValue(entity);
    }

    /**
     * 设置缓存地址
     */
    public void setCacheLocation(int index, CargoPublishEntity.LocationEntity entity) {
        if (mCacheLocationList != null && index < mCacheLocationList.length) {
            mCacheLocationList[index] = entity;
        }
    }

    /**
     * 获取装货/卸货地址信息
     */
    public void getLocationListByLoadMode(List<CargoPublishEntity.LocationEntity> list, String mode) {
        list.clear();
        switch (mode) {
            case "11"://一装一卸
                list.add(mCacheLocationList[0]);
                list.add(mCacheLocationList[3]);
                break;
            case "12"://一装两卸
                list.add(mCacheLocationList[0]);
                list.add(mCacheLocationList[2]);
                list.add(mCacheLocationList[3]);
                break;
            case "21"://两装一卸
                list.add(mCacheLocationList[0]);
                list.add(mCacheLocationList[1]);
                list.add(mCacheLocationList[3]);
                break;
            case "22"://两装两卸
                list.add(mCacheLocationList[0]);
                list.add(mCacheLocationList[1]);
                list.add(mCacheLocationList[2]);
                list.add(mCacheLocationList[3]);
                break;
        }
    }

    /**
     * 获取初始定位，给装货地赋值
     */
    public void getCurrentLocation(Context context) {
        DialogHelper.showProgressDialog(context, "请求中...");
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data == null) {
                    ldLocation.postValue(false);
                    return;
                }
                setSendLocation(context);
            }
        });
    }

    /**
     * 设置发货地定位
     */
    private void setSendLocation(Context context) {
        //查找地址下标
        if (LocationUtil.isOpenLocation(context)) {
            //设置经纬度
            double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
            double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
            if (lat != 0 && log != 0) {
                mCacheLocationList[0].setLongitude(log);
                mCacheLocationList[0].setLatitude(lat);
            } else {
                //未获取定位数据时不填入默认信息
                ldLocation.postValue(false);
                return;
            }
            //查找省市区no
            String provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
            String cityName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.City, "乌鲁木齐");
            String areaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Area, "天山");
            String address = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AoiName, "");
            AddressEntity[] code = AddressHelper.getInstance().findCode(provinceName, cityName, areaName);
            if (code != null && code.length >= 3) {
                //设置省市区简称no
                if (code[0] != null) {
                    mCacheLocationList[0].setProvinceNo(code[0].getNo());
                    mCacheLocationList[0].setProvince(code[0].getSimpleName());
                }
                if (code[1] != null) {
                    mCacheLocationList[0].setCityNo(code[1].getNo());
                    mCacheLocationList[0].setCity(code[1].getSimpleName());
                }
                if (code[2] != null) {
                    mCacheLocationList[0].setDistrictNo(code[2].getNo());
                    mCacheLocationList[0].setDistrict(code[2].getSimpleName());
                }
            }
            mCacheLocationList[0].setAddress(address);
            ldLocation.postValue(true);
        } else {
            ldLocation.postValue(false);
        }
    }

    /**
     * 计算总运程
     */
    public void calculateLineDistance(List<CargoPublishEntity.LocationEntity> list, String handleTypeNo) {
        if (list == null || list.size() < 2) {
            ldDistance.postValue(null);
            return;
        }
        //检查是否全部填写了距离
        boolean isAllHaveLatLng = true;
        for (CargoPublishEntity.LocationEntity entity : list) {
            if (entity.getLatitude() == 0 || entity.getLongitude() == 0) {
                isAllHaveLatLng = false;
                break;
            }
        }
        //是否全部填写了距离
        if (!isAllHaveLatLng) {
            ldDistance.postValue(null);
            return;
        }
        //计算总运程
        calculateDistance(list, handleTypeNo);
    }

    /**
     * 装载方式
     */
    private void calculateDistance(List<CargoPublishEntity.LocationEntity> list, String handleTypeNo) {
        Map<String, Object> map = new HashMap<>();
        //装卸方式 一装一卸 11 ,一装两卸 12 , 两装一卸 21, 两装两卸 22
        map.put("handleType", handleTypeNo);
        for (CargoPublishEntity.LocationEntity entity : list) {
            switch (entity.getItemType()) {
                case SingleItemConstant.TYPE_ONE:
                    map.put("latitude", entity.getLatitude());
                    map.put("longitude", entity.getLongitude());
                    break;
                case SingleItemConstant.TYPE_TWO:
                    map.put("viaSendLatitude", entity.getLatitude());
                    map.put("viaSendLongitude", entity.getLongitude());
                    break;
                case SingleItemConstant.TYPE_THREE:
                    map.put("viaDestLatitude", entity.getLatitude());
                    map.put("viaDestLongitude", entity.getLongitude());
                    break;
                case SingleItemConstant.TYPE_FOUR:
                    map.put("destLatitude", entity.getLatitude());
                    map.put("destLongitude", entity.getLongitude());
                    break;
            }
        }
        NewAPIManager.getInstance().getLogisticsAPI().calculateDistance(map).enqueue(new ICallBack<BaseEntity<CargoDistanceEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CargoDistanceEntity> data) {
                ldDistance.postValue(data.getData());
            }
        });
    }

    /**
     * 发布货源
     */
    public void releaseCargo(Context context, TextView view, CargoPublishEntity entity) {
        if (entity.getBeginTime() == 0) {
            MToast.showToast(getApplication(), "请先填写装货时间");
            return;
        }

        if (TextUtils.isEmpty(entity.getGoodsModeName()) || entity.getGoodsWeight() == 0f) {
            MToast.showToast(getApplication(), "请先填写货物信息");
            return;
        }
        //判断运费
        if (entity.getFreight() == 0 || TextUtils.isEmpty(entity.getPayType())) {
            MToast.showToast(getApplication(), "请先填写费用要求");
            return;
        }
        //计量单位”方“与 单价50吨不相符，请重新选择计量单位
        if (entity.getFreightMode() == CargoPublishEntity.FreightMode.MODE_WEIGHT && entity.getGoodsWeight() == 0) {
            String tip = String.format("计量单位”吨“与单价%s方不相符，请重新选择计量单位", NumberUtil.trim0(entity.getGoodsVolume()));
            showFreightTipDialog(context, tip);
            return;
        }
        if (entity.getFreightMode() == CargoPublishEntity.FreightMode.MODE_VOLUME && entity.getGoodsVolume() == 0) {
            String tip = String.format("计量单位”方“与单价%s吨不相符，请重新选择计量单位", NumberUtil.trim0(entity.getGoodsWeight()));
            showFreightTipDialog(context, tip);
            return;
        }
        //判断报价资格
        if (entity.getQuotationQualification() == null) {
            MToast.showToast(getApplication(), "请先填写报价资格");
            return;
        }
        //判断联系信息
        if (ArrayUtil.isNullOrEmpty(entity.getContactInfo())) {
            MToast.showToast(getApplication(), "请先填写联系信息");
            return;
        }
        //判断装卸方式提示具体信息
        if ("11".equals(entity.getLoadModeNo()) && entity.getLocationList().size() == 2) {
            if (entity.getLocationList().get(0).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写发货信息");
                return;
            }
            if (entity.getLocationList().get(1).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写收货信息");
                return;
            }
        }
        if ("12".equals(entity.getLoadModeNo()) && entity.getLocationList().size() == 3) {
            if (entity.getLocationList().get(0).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写发货信息");
                return;
            }
            if (entity.getLocationList().get(1).getLatitude() == 0 || entity.getLocationList().get(2).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写收货信息");
                return;
            }
        }
        if ("21".equals(entity.getLoadModeNo()) && entity.getLocationList().size() == 3) {
            if (entity.getLocationList().get(0).getLatitude() == 0 || entity.getLocationList().get(1).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写发货信息");
                return;
            }
            if (entity.getLocationList().get(2).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写收货信息");
                return;
            }
        }
        if ("22".equals(entity.getLoadModeNo()) && entity.getLocationList().size() == 4) {
            if (entity.getLocationList().get(0).getLatitude() == 0 || entity.getLocationList().get(1).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写发货信息");
                return;
            }
            if (entity.getLocationList().get(2).getLatitude() == 0 || entity.getLocationList().get(3).getLatitude() == 0) {
                MToast.showToast(getApplication(), "请先填写收货信息");
                return;
            }
        }

        if (mCacheLocationList.length > 0) {
            if (TextUtils.isEmpty(mCacheLocationList[0].getContact()) || TextUtils.isEmpty(mCacheLocationList[0].getTelPhone())) {
                MToast.showToast(getApplication(), "请先填写装车对接人信息");
                return;
            }
        }

        if (entity.getPattern() == 1) {
            //判断竞价结束时间
            if (entity.getBiddingEndTime() == 0) {
                MToast.showToast(getApplication(), "请先填写报价截止时间");
                return;
            }
            if (entity.getBiddingEndTime() < System.currentTimeMillis()) {
                MToast.showToast(getApplication(), "报价截止时间不能小于当前时间");
                return;
            }
            if (entity.getEndTime() != 0) {
                //计算是否是同一天
                String biddingEndTime = DateUtils.stampToDay5(entity.getBiddingEndTime());
                String endTime = DateUtils.stampToDay5(entity.getEndTime());
                boolean isSameDay = !TextUtils.isEmpty(endTime) && endTime.equals(biddingEndTime);
                //判断是否是同一天，同一天忽略截止时间判断
                if (!isSameDay && entity.getBiddingEndTime() > entity.getEndTime()) {
                    MToast.showToast(getApplication(), "报价截止时间不能大于装货结束时间");
                    return;
                }
            } else if (entity.getEndTime() == 0 && entity.getBiddingEndTime() > DateUtils.getCustomizeDayNight(0, entity.getBeginTime()).getTime()) {
                //只有开始时间的情况下用开始时间当天的23:59:59与报价结束时间做判断
                MToast.showToast(getApplication(), "报价截止时间不能大于装货结束时间");
                return;
            }
        }
        //组装请求对象
        Map<String, Object> map = new HashMap<>();
        //编辑时传货源no
        if (!TextUtils.isEmpty(entity.getNo())) {
            map.put("no", entity.getNo());
        }
        if (entity.getId() != 0) {
            map.put("id", entity.getId());
        }
        //货源发布模式 0 普通模式  1 竞价模式
        map.put("pattern", entity.getPattern());
        //装卸方式编号
        map.put("handleTypeNo", entity.getLoadModeNo());
        //装货时间
        map.put("shipmentTime", entity.getBeginTime());
        //装货结束时间
        if (entity.getEndTime() != 0) {
            map.put("shipmentEndTime", entity.getEndTime());
        }
        //2.0.8 修改字段名称 货物类型编号
        map.put("goodsTypeNo", entity.getGoodsModeNo());
        map.put("secondGoodsTypeNo", entity.getSecondGoodsTypeNo());
        //货物重量
        if (entity.getGoodsWeight() != 0) {
            map.put("weight", entity.getGoodsWeight());
        }
        //货物体积
        if (entity.getGoodsVolume() != 0) {
            map.put("volume", entity.getGoodsVolume());
        }
        //运费信息
        map.put("freight", entity.getFreight());
        //运费方式 1：元/趟，2：元/吨，3：元/方
        map.put("freightUnit", entity.getFreightMode());
        //运费总价
        map.put("allFreight", entity.getTotalFreight());
        //新增字段json
        if (entity.getCustomList() != null && entity.getCustomList().size() > 0) {
            JsonObject field = new JsonObject();
            for (SingleItemEntity diy : entity.getCustomList()) {
                field.addProperty(diy.getLeftString(), diy.getRightString());
            }
            map.put("addField", field.toString());
        }
        //根据当前登录身份填写企业/团队数据，2.0.2.1增加个人发布普通货源
        if (UserOperating.getInstance().isCompany()) {
            map.put("companyNo", entity.getCompanyNo());
            map.put("companyname", entity.getCompany());
        } else if (UserOperating.getInstance().isTeam()) {
            map.put("teamNo", entity.getCompanyNo());
            map.put("teamName", entity.getCompany());
        } else if (UserOperating.getInstance().isPersonal()) {
            //个人发布普通货源
            map.put("terminal", 3);
        }
        //是否推送车主 0 不推送  1推送(2.0.1更改为固定不推送)
        map.put("isTrue", 0);
        //2.0.1新增履约保证金
        if (entity.getPerformanceBond() != null && entity.getPerformanceBond() != 0) {
            map.put("performanceBond", entity.getPerformanceBond());
        }
        //2.0.1新增付款约定
        //支付方式
        map.put("payType", entity.getPayType());
        //发票要求
        map.put("invoice", entity.getInvoice());
        //发票要求No
        map.put("invoiceNo", entity.getInvoiceNo());
        //税率
        map.put("tariff", entity.getTariff());
        //开票公司名称
        map.put("invoicingCompanyName", entity.getInvoicingCompanyName());
        //开票税号
        map.put("invoicingTaxNumber", entity.getInvoicingTaxNumber());
        //开票地址
        map.put("invoicingAddress", entity.getInvoicingAddress());
        //开票企业电话
        map.put("invoicingCompanyPhone", entity.getInvoicingCompanyPhone());
        //开票开户银行
        map.put("invoicingBank", entity.getInvoicingBank());
        //开票银行账户
        map.put("invoicingBankAccount", entity.getInvoicingBankAccount());
        //开票开户行号
        map.put("invoicingBankNumber", entity.getInvoicingBankNumber());
        //发货/收货信息
        for (CargoPublishEntity.LocationEntity locationEntity : entity.getLocationList()) {
            switch (locationEntity.getItemType()) {
                case SingleItemConstant.TYPE_ONE://发货地
                    //发货人
                    map.put("sendPeople", DefaultUtil.getString(locationEntity.getContact()));
                    //发货人电话
                    map.put("sendPhone", DefaultUtil.getString(locationEntity.getTelPhone()));
                    //2.0.1新增发货单位
                    map.put("sendGoodsUnit", DefaultUtil.getString(locationEntity.getGoodsUnit()));
                    //发货地地址信息
                    map.put("longitude", locationEntity.getLongitude());
                    map.put("latitude", locationEntity.getLatitude());
                    map.put("provinceNo", locationEntity.getProvinceNo());
                    map.put("provinceName", locationEntity.getProvince());
                    map.put("cityNo", locationEntity.getCityNo());
                    map.put("cityName", locationEntity.getCity());
                    map.put("districtNo", locationEntity.getDistrictNo());
                    map.put("districtName", locationEntity.getDistrict());
                    map.put("detailAddress", locationEntity.getAddress());
                    break;
                case SingleItemConstant.TYPE_TWO://途径发货地
                    //途径发货地地址信息
                    map.put("viaSendLongitude", locationEntity.getLongitude());
                    map.put("viaSendLatitude", locationEntity.getLatitude());
                    map.put("viaSendProvinceNo", locationEntity.getProvinceNo());
                    map.put("viaSendProvinceName", locationEntity.getProvince());
                    map.put("viaSendCityNo", locationEntity.getCityNo());
                    map.put("viaSendCityName", locationEntity.getCity());
                    map.put("viaSendDistrictNo", locationEntity.getDistrictNo());
                    map.put("viaSendDistrictName", locationEntity.getDistrict());
                    map.put("viaSendDetailAddress", locationEntity.getAddress());
                    break;
                case SingleItemConstant.TYPE_THREE://途径收货地
                    //途径收货地地址信息
                    map.put("viaDestLongitude", locationEntity.getLongitude());
                    map.put("viaDestLatitude", locationEntity.getLatitude());
                    map.put("viaDestProvinceNo", locationEntity.getProvinceNo());
                    map.put("viaDestProvinceName", locationEntity.getProvince());
                    map.put("viaDestCityNo", locationEntity.getCityNo());
                    map.put("viaDestCityName", locationEntity.getCity());
                    map.put("viaDestDistrictNo", locationEntity.getDistrictNo());
                    map.put("viaDestDistrictName", locationEntity.getDistrict());
                    map.put("viaDestDetailAddress", locationEntity.getAddress());
                    break;
                case SingleItemConstant.TYPE_FOUR://收货地
                    //收货人
                    map.put("receptionPeople", DefaultUtil.getString(locationEntity.getContact()));
                    //收货人电话
                    map.put("receptionPhone", DefaultUtil.getString(locationEntity.getTelPhone()));
                    //2.0.1新增收货单位
                    map.put("receiveGoodsUnit", DefaultUtil.getString(locationEntity.getGoodsUnit()));
                    //收货地地址信息
                    map.put("destLongitude", locationEntity.getLongitude());
                    map.put("destLatitude", locationEntity.getLatitude());
                    map.put("destProvinceNo", locationEntity.getProvinceNo());
                    map.put("destProvinceName", locationEntity.getProvince());
                    map.put("destCityNo", locationEntity.getCityNo());
                    map.put("destCityName", locationEntity.getCity());
                    map.put("destDistrictNo", locationEntity.getDistrictNo());
                    map.put("destDistrictName", locationEntity.getDistrict());
                    map.put("destDetailAddress", locationEntity.getAddress());
                    break;
            }
        }
        //运程
        if (entity.getDistance() != null) {
            //发货地-途径发货地距离
            map.put("firstDistance", entity.getDistance().getFirstDistance());
            //途径发货地-途径目的地距离
            map.put("secondDistance", entity.getDistance().getSecondDistance());
            //途径目的地-目的地距离
            map.put("thirdDistance", entity.getDistance().getThirdDistance());
            //总距离
            map.put("totalDistance", entity.getDistance().getTotalDistance());
        }
        //竞价模式参数
        if (entity.getPattern() == 1) {
            //报价截止时间
            map.put("endTime", entity.getBiddingEndTime());
        }
        //2.0.6新增字段
        //装车要求
        if (entity.getRequire() != 0) {
            map.put("loadRequire", entity.getRequire());
        }
        //装货开始时间点
        map.put("startPointTime", entity.getStartPointTime());
        if (entity.getEndPointTime() != 0) {
            //装货结束时间点
            map.put("endPointTime", entity.getEndPointTime());
        }
        //2.0.8 新增字段
        //货物规格
        map.put("specification", entity.getSpecification());
        //是否含税 0 不含 1 含税 null 未填写
        if (entity.getIncludeTax() != null) {
            map.put("includeTax", entity.getIncludeTax());
        }
        //货损约定(吨)
        map.put("damagePromise", entity.getDamageAgreement());
        ////货损赔偿(元/吨)
        map.put("damageCompensation", entity.getDamageCompensation());
        //其他结算要求
        map.put("otherSettlementRequire", entity.getOtherSettlementReq());
        //报价资格 1 企业 2 团队 3 司机 ，多选英文逗号隔开
        StringBuilder builder = new StringBuilder();
        if (entity.getQuotationQualification() != null && entity.getQuotationQualification().length == 3) {
            if (entity.getQuotationQualification()[0]) {
                builder.append(",").append("1");
            }
            if (entity.getQuotationQualification()[1]) {
                builder.append(",").append("2");
            }
            if (entity.getQuotationQualification()[2]) {
                builder.append(",").append("3");
            }
        }
        map.put("offerType", builder.length() == 0 ? "" : builder.substring(1));
        //注册资本(万元)
        map.put("registeredMoney", entity.getRegisteredCapital());
        //车队规模(辆)
        map.put("motorcadeSize", entity.getFleetSize());
        //运输资质
        map.put("transportationQualification", entity.getTransportationQualification());
        //其他要求
        map.put("otherOfferRequire", entity.getOtherRequirements());
        //项目名称
        map.put("projectName", entity.getProjectName());
        //项目地址
        map.put("projectAddress", entity.getProjectAddress());
        //项目描述
        map.put("projectDesc", entity.getProjectDesc());
        //运输要求
        map.put("transportationQuire", entity.getTransportReq());
        //甲方责任约定
        map.put("partyDuty", entity.getPartyAAgreement());
        //乙方责任约定
        map.put("secondPartyDuty", entity.getPartyBAgreement());
        //违约约定
        map.put("renegePromise", entity.getBreachOfContract());
        //合同终止约定
        map.put("endContractPromise", entity.getTerminationAgreement());
        //联系信息 一个或多个联系人+联系电话
        map.put("contactInfo", entity.getContactInfo());
         //联系人
        map.put("connection", entity.getConnection());
                //联系人电话
        map.put("connectionPhone", entity.getConnectionPhone());
        view.setEnabled(false);
        DialogHelper.showProgressDialog(context, "数据加载中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().releaseCargo(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                //发布成功
                //判断是否是编辑，编辑直接返回来源页，新增跳转详情页
                if (TextUtils.isEmpty(entity.getNo())) {
                    //设置货源no
                    if (data.getData() instanceof String) {
                        entity.setNo((String) data.getData());
                    }
                    //跳转详情页
                    FreightPrjDetailActivity.start(context, entity.getNo(), false, true);
                }
                EventBus.getDefault().post(LogisticsEvent.make(EventConstant.EVENT_CARGO_RELEASE_SUCCESS, null));
                ((Activity) context).finish();
            }

            @Override
            public void onFail() {
                MToast.showToast(getApplication(), "操作失败");
            }

            @Override
            public void onFinally() {
                super.onFinally();
                view.setEnabled(true);
            }
        });
    }

    /**
     * 运费提示弹窗
     */
    private void showFreightTipDialog(Context context, String tip) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(tip)
                .confirmCallback(v -> ldJump.postValue(0))
                .show();
    }
}
